package api

import (
	"github.com/gogf/gf/errors/gerror"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/net/ghttp"
	"github.com/gogf/gf/util/gvalid"
	"shrimp-blog-server/app/model"
	"shrimp-blog-server/utils"
)

type UserParams struct {
	Username string `json:"username"`
	Email    string `json:"email" v:"email@required|email#邮箱不能为空|邮箱格式不正确"`
	Password string `json:"password" v:"password@required|password2#密码不能为空|密码格式不合法"`
}

func (*apiUser) Login(req *ghttp.Request) {
	var params UserParams
	// 使用结构体定义的校验规则和错误提示进行校验
	_ = req.Parse(&params)
	if e := gvalid.CheckStructWithData(req.Context(), UserParams{}, params, nil); e != nil {
		g.Dump(e.Items())
		g.Log().Info(gerror.Current(e))
		utils.Response.ErrorResponseExit(req, gerror.Current(e).Error())
	}
	// 校验用户名和密码
	userService.Login(req, params.Email, params.Password)
}

func (*apiUser) Register(req *ghttp.Request) {
	var params UserParams
	// 使用结构体定义的校验规则和错误提示进行校验
	_ = req.Parse(&params)
	if e := gvalid.CheckStructWithData(req.Context(), UserParams{}, params, nil); e != nil {
		g.Dump(e.Items())
		g.Log().Info(gerror.Current(e))
		utils.Response.ErrorResponseExit(req, gerror.Current(e).Error())
	}
	// 校验用户名和密码
	userService.Register(req, params.Username, params.Email, params.Password)
}

func (*apiUser) Post(req *ghttp.Request) {
	var params UserParams
	// 使用结构体定义的校验规则和错误提示进行校验
	_ = req.Parse(&params)
	if e := gvalid.CheckStructWithData(req.Context(), UserParams{}, params, nil); e != nil {
		g.Dump(e.Items())
		g.Log().Info(gerror.Current(e))
		utils.Response.ErrorResponseExit(req, gerror.Current(e).Error())
	}

	user := model.User{
		Username: params.Username,
		Password: params.Password,
		Email:    params.Email,
	}
	userService.Insert(req, user)
}

func (*apiUser) Get(req *ghttp.Request) {
	userService.GetUserByID(req, getQueryParamID(req)...)
}

func (*apiUser) Delete(req *ghttp.Request) {
	userService.Delete(req, getQueryParamID(req)...)
}

func (*apiUser) Put(req *ghttp.Request) {
	var users []model.User
	_ = req.Parse(&users)
	if users == nil {
		utils.Response.ErrorResponseExit(req, "用户信息参数错误")
	}
	for i := range users {
		if e := gvalid.CheckStructWithData(req.Context(), UserParams{}, users[i], nil); e != nil {
			g.Dump(e.Items())
			g.Log().Info(gerror.Current(e))
			utils.Response.ErrorResponseExit(req, gerror.Current(e).Error())
		}
	}
	userService.Update(req, users...)
}

func (*apiUser) GetListPage(req *ghttp.Request) {
	userService.GetUserPage(req, getPage(req))
}
